<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;

class SpecItem extends Base
{
    protected $name = 'spec_item';

    public function spec()
    {
        return $this->hasOne(Spec::class, 'id', 'spec_id');
    }


    public static function setSpec($id, $value, $item_id = [])
    {
        try {
            $item = explode(',', $value);
            if ($item_id) {
                foreach ($item_id as $k => $v) {
                    $info = parent::where('id', $v)->find();

                    if ($info) {
                        if ($info['name'] != $item[$k]) {
                            $info['name'] = $item[$k];
                            $info->save();

                            self::productExamineAgain($v);
                        }
                    }
                }
            }
            $spec_item = parent::where('spec_id', $id)->select();
            foreach ($spec_item as $val) {
                if (in_array($val['name'], $item)) {
                    $key = array_search($val['name'], $item);
                    unset($item[$key]);
                } else {
                    parent::destroy(['id' => $val['id']]);
                    self::productExamineAgain($val['id']);
                }
            }
            if ($item) {
                $all = [];
                foreach ($item as $v) {
                    $all[] = [
                        'spec_id' => $id,
                        'name' => $v
                    ];
                }
                Db::name('spec_item')->insertAll($all);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 商品再次审核
     * @param $sku_id
     * @return bool
     */
    public static function productExamineAgain($sku_id)
    {
        $pids = ProductSpecValue::whereRaw("FIND_IN_SET($sku_id,REPLACE(sku_id,'-',','))")->column('pid');
        Product::whereIn('id', $pids)->save(['examine_status'=>1]);//规格变更，对应商品重新审核

        return true;
    }

    public static function getSpecItemName($str)
    {
        $spec_item = explode('-', $str);
        $arr = [];
        foreach ($spec_item as $v) {
            $arr[] = parent::where('id', $v)->value('name');
        }
        return implode('-', $arr);
    }


}
